<template>
  <div class="login-form-wrapper">
    <div class="login-form-title">{{ '' }}</div>
    <div class="login-form-sub-title">{{ '' }}</div>
    <div class="login-form-error-msg">{{ errorMessage }}</div>
    <AForm
      ref="loginForm"
      :model="userInfo"
      class="login-form"
      layout="vertical"
      @submit="handleSubmit"
    >
      <AFormItem
        field="userAccount"
        :rules="[{ required: true, message: '请输入用户名' }]"
        :validate-trigger="['change', 'input', 'blur']"
        hide-label
      >
        <AInput
          v-model="userInfo.userAccount"
          placeholder="请输入用户名"
          allow-clear
          @blur="getCompanyUser"
        >
          <template #prefix>
            <icon-user-group />
          </template>
        </AInput>
      </AFormItem>
      <AFormItem
        field="tenantId"
        :rules="[{ required: true, message: '请选择企业' }]"
        :validate-trigger="['change', 'blur']"
        hide-label
      >
        <ASelect v-model="userInfo.tenantId" allow-search placeholder="请选择企业" allow-clear>
          <template #prefix>
            <icon-user />
          </template>
          <AOption
            v-for="(item, index) in comUser"
            :key="index"
            :value="item.tenantId"
            :label="item.tenantName"
          ></AOption>
        </ASelect>
      </AFormItem>
      <AFormItem
        field="userPassword"
        :rules="[{ required: true, message: '请输入密码' }]"
        :validate-trigger="['input', 'blur']"
        hide-label
      >
        <AInput-password v-model="userInfo.userPassword" placeholder="请输入密码" allow-clear>
          <template #prefix>
            <icon-lock />
          </template>
        </AInput-password>
      </AFormItem>
      <ASpace :size="16" direction="vertical">
        <AButton type="primary" html-type="submit" long :loading="loading"> 登录 </AButton>
      </ASpace>
    </AForm>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { Message } from '@arco-design/web-vue'
import { ValidatedError } from '@arco-design/web-vue/es/form/interface'
import { useUserStore } from '@renderer/store'
import useLoading from '@renderer/hooks/loading'
import { companyUserType, getCompanyUserList, type LoginData } from '@renderer/api/user'

const router = useRouter()
const errorMessage = ref('')
const { loading, setLoading } = useLoading()
const userStore = useUserStore()

const loginConfig = useStorage('login-config', {
  rememberPassword: true,
  username: '', // 演示默认值
  password: '' // demo default value
})
const userInfo = ref<LoginData>({
  userAccount: '',
  tenantId: '',
  loginVerifyType: 0,
  userPassword: ''
})

const handleSubmit = async ({
  errors,
  values
}: {
  errors: Record<string, ValidatedError> | undefined
  values: Record<string, any>
}) => {
  if (loading.value) return
  if (!errors) {
    setLoading(true)
    try {
      await userStore.login(values as LoginData)
      const { ...othersQuery } = router.currentRoute.value.query
      router.push({
        name: 'company',
        query: {
          ...othersQuery
        }
      })

      Message.success('登录成功')
      const { rememberPassword } = loginConfig.value
      const { username, password } = values
      // 实际生产环境需要进行加密存储。
      // The actual production environment requires encrypted storage.
      loginConfig.value.username = rememberPassword ? username : ''
      loginConfig.value.password = rememberPassword ? password : ''
    } catch (err) {
      errorMessage.value = (err as Error).message
    } finally {
      setLoading(false)
    }
  }
}

// 获取账号企业列表
const comUser = ref<companyUserType['list']>([])
const getCompanyUser = () => {
  getCompanyUserList({ userAccount: userInfo.value.userAccount }).then((res) => {
    comUser.value = res.data.list
  })
}

// const route = useRoute()
onMounted(() => {
  // console.log(router.options.routes)
})
</script>

<style lang="less" scoped>
.login-form {
  &-wrapper {
    width: 320px;
  }

  &-title {
    color: var(--color-text-1);
    font-weight: 500;
    font-size: 24px;
    line-height: 32px;
  }

  &-sub-title {
    color: var(--color-text-3);
    font-size: 16px;
    line-height: 24px;
  }

  &-error-msg {
    height: 32px;
    color: rgb(var(--red-6));
    line-height: 32px;
  }

  &-password-actions {
    display: flex;
    justify-content: space-between;
  }

  &-register-btn {
    color: var(--color-text-3) !important;
  }
}
</style>
